#define _CRT_SECURE_NO_WARNINGS 1
#include "List.h"

ListNode* BuyLTNode(LTDataType x)
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		return NULL;
	}
	
	newnode->data = x;
	newnode->next = NULL;
	newnode->prev = NULL;

	return newnode;
}

ListNode* LTInit()
{
	ListNode* head = BuyLTNode(-1);
	head->next = head;
	head->prev = head;
	return head;
}

void LTPushBack(ListNode* phead, LTDataType x)
{
	assert(phead);
	ListNode* newnode = BuyLTNode(x);
	ListNode* tail = phead->prev;
	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = phead;
	phead->prev = newnode;

}

void LTPrint(ListNode* phead)
{
	assert(phead);
	ListNode* cur = phead->next;
	printf("<=head=>");
	while (cur != phead)
	{
		printf("%d<=>",cur->data);
		cur = cur->next;
	}
	printf("\n");
}

bool LTEmpty(ListNode* phead)
{
	assert(phead);

	return phead->next == phead;
}

void LTPopBack(ListNode* phead)
{
	assert(phead);
	assert(!LTEmpty(phead));
	ListNode* tail = phead->prev;
	ListNode* tailPrev = tail->prev;
	free(tail);
	tail = NULL;
	tailPrev->next = phead;
	phead->prev = tailPrev;

}

void LTPushFront(ListNode* phead, LTDataType x)
{
	assert(phead);
	ListNode* first = phead->next;
	ListNode* newnode = BuyLTNode(x);
	phead->next = newnode;
	newnode->prev = phead;
	newnode->next = first;
	first->prev = newnode;

}

void LTPopFront(ListNode* phead)
{
	assert(phead);
	assert(!LTEmpty(phead));
	ListNode* cur = phead->next;
	ListNode* next = cur->next;
	free(cur);
	cur = NULL;
	phead->next = next;
	next->prev = phead;
}

ListNode* LTFindNode(ListNode* phead, LTDataType x)
{
	ListNode* cur = phead->next;
	while (cur != phead)
	{
		if (cur->data == x)
			return cur;
		cur = cur->next;
	}
	return NULL;
}

void LTInsertBefore(ListNode* pos, LTDataType x)
{
	ListNode* posPrev = pos->prev;
	ListNode* newnode = BuyLTNode(x);
	posPrev->next = newnode;
	newnode->prev = posPrev;
	newnode->next = pos;
	pos->prev = newnode;

}

void LTErase(ListNode* pos)
{
	ListNode* posPrev = pos->prev;
	ListNode* posNext = pos->next;
	free(pos);
	pos = NULL;
	posPrev->next = posNext;
	posNext->prev = posPrev;
}

void LTDestroy(ListNode** pphead)
{
	assert(pphead);
	ListNode* cur = (*pphead)->next;
	ListNode* next = (*pphead)->next;
	while (cur != *pphead)
	{
		next = cur->next;
		free(cur);
		cur = next;
	}

	free(*pphead);
	(*pphead)->next = NULL;
	(*pphead)->prev = NULL;
}